    package cn.jiahua.test2;

    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    public class SaleTicketDemo2 {

        public static void main(String[] args) {

            Ticket  ticket =new Ticket();

            //创建多线程，JDK8新特性 lamda创建线程
            new Thread(()->{
                for (int i=0;i<30;i++){
                    ticket.saleTicket();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },String.valueOf("线程1")).start();


            new Thread(()->{
                for (int i=0;i<30;i++){
                    ticket.saleTicket();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },String.valueOf("线程2")).start();

            new Thread(()->{
                for (int i=0;i<30;i++){
                    ticket.saleTicket();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },String.valueOf("线程3")).start();
        }
    }


    class  Ticket{
        private int num=30;
        Lock lock =new ReentrantLock();

        public  void saleTicket(){
            lock.lock();   //上锁
            try{
                if(num>0){
                    System.out.println(Thread.currentThread().getName()+"买到"+num--+"张票,剩余"+num);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock() ; //解锁

            }
        }

    }